import DataDict from '@/utils/dict/index.ts'

import { reqDictsDataByType } from '@/api/system/dict/data.ts'
import { App } from 'vue'
import DictMeta from '@/utils/dict/DictMeta.ts'
import { useDictStore } from '@/store/modules/dict.ts'

function searchDictByKey(dict, key) {
  if (key == null && key == '') {
    return null
  }
  try {
    for (let i = 0; i < dict.length; i++) {
      if (dict[i].key === key) {
        return dict[i].value
      }
    }
  } catch (e) {
    return null
  }
}

/*此处是安装字典的位置*/
function install(app: App) {
  console.log('字典安装...')
  /*app.use() 方法来将 DataDict 插件安装到 Vue.js 应用程序中*/
  /*插件的选项以对象形式作为第二个参数传递。*/
  app.use(DataDict, {
    /*这里传的值会在utils/dict/index中被options接收到*/
    metas: {
      '*': {
        request(dictMeta: DictMeta) {
          const dictStore = useDictStore()
          const storeDict = searchDictByKey(dictStore.dict, dictMeta.type)
          if (storeDict) {
            /*就可以直接返回*/
            return new Promise((resolve) => {
              resolve(storeDict)
            })
          } else {
            return new Promise((resolve, reject) => {
              reqDictsDataByType(dictMeta.type)
                .then((res) => {
                  dictStore.setDict(dictMeta.type, res.data)
                  resolve(res.data)
                })
                .catch((error) => {
                  reject(error)
                })
            })
          }
            return reqDictsDataByType(dictMeta.type).then((req: any) => {
                        return req.data;
                    })
        },
        labelField: 'dictLabel',
        valueField: 'dictValue',
      },
    },
  })
}

export default {
  install,
}
